import socket
import os
from urllib import parse
from hashlib import sha256


class File(object):
    """
    requests content uploader
    """
    def __init__(self, base_path=None, *args, **kwargs):
        self.base_path = base_path if base_path else ''
        if not self.base_path.endswith('/'):
            self.base_path += '/'

    def make_dirs(self, path):
        dir_name = os.path.dirname(path)
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)

    def save(self, content, file_type=None, path=None, key=None):
        if path:
            path = self.base_path + path
        self.make_dirs(path)
        if isinstance(content, str):
            content = content.encode('utf-8')
        checksum = sha256(content).hexdigest()
        file_name = checksum[:10] + file_type
        try:
            file = open(path+file_name, 'wb')
            file.write(content)
            file.close()
        except Exception as tmp:
            print(tmp)
            return False
        return {'checksum': checksum, 'path': path, 'file_name': file_name,
                'key': key, 'hostname': socket.gethostname()}
